package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.constants.BasicErrorCodes;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.DateTimeUtil;
import com.cloudbroker.bcs.common.util.EnumUtil;
import com.cloudbroker.bcs.common.util.MD5Util;
import com.cloudbroker.bcs.common.util.RandomUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.FuncAuthCodeForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.FuncLoginForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.FuncPasswordResetForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.FuncRegisterForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.FuncUserUpdateForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.request.base.UCForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.response.AuthCodeBackVo;
import com.cloudbroker.bcs.csvc.uc.api.vo.response.CheckRegisterBackVo;
import com.cloudbroker.bcs.csvc.uc.api.vo.response.UIDBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.CommonErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.FavoriteErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.HSBCSACTIVITYErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.RollingMsgErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.AccessTokenType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.ApplyStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.CustomerStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.NoticeSendStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.BrokerLoginType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.BrokerType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.CommonType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.LoginErrType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.NoticeType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.VerifySource;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.ViewpointPublicType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.WxAccountType;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.PageVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.UserManagerBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.BatchImportBrokerBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.BrokerAccountListBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.BrokerRegFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.CustomerIdFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.ImgVerifyFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.LoginFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.NewsQueryFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.NewsSaveFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.OnlinenumFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.QueryAccountListFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.RegisterOrLoginBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.RegisternumFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.SendSMSBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.WhiteAccountListFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.WhiteListBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BatchImportBrokerForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BatchImportBrokerListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BrokerAccountInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BrokerAccountListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BrokerDetailForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BrokerRegCheckForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BrokerRegForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BrokerStatusChangeForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.ChangePasswordForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.CustomerIdForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.FollowBrokerForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.ImgVerifyForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.LoginForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.OperatorWhiteListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.PachSendSMSForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.QueryAccountListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.RegisterOrLoginForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.ResetPasswordForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.SendSMSForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.TenantForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.WebsiteRegForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.WhiteAccountListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.WhiteListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.WhiteListFormData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.vo.RegisteForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.vo.ExtendGroupBuildDefaultForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.GetChatroomAddrForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.UserInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.response.GetChatroomAddrBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.BrokerInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.NewsQueryForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.NewsSaveForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.NoticeInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.business.ExtendGroupT2BizService;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.YunxinT2BizService;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.CacheKeys;
import com.cloudbroker.bcs.platform.dav.common.constant.SysContants;
import com.cloudbroker.bcs.platform.dav.common.constant.type.PlatformType;
import com.cloudbroker.bcs.platform.dav.common.util.CacheHelper;
import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.BrokerAction;
import com.cloudbroker.bcs.platform.dav.middle.entity.BrokerCheck;
import com.cloudbroker.bcs.platform.dav.middle.entity.BrokerManager;
import com.cloudbroker.bcs.platform.dav.middle.entity.ChatRoom;
import com.cloudbroker.bcs.platform.dav.middle.entity.Customer;
import com.cloudbroker.bcs.platform.dav.middle.entity.CustomerBrokerRel;
import com.cloudbroker.bcs.platform.dav.middle.entity.News;
import com.cloudbroker.bcs.platform.dav.middle.entity.NoticeMsg;
import com.cloudbroker.bcs.platform.dav.middle.entity.Tenant;
import com.cloudbroker.bcs.platform.dav.middle.entity.ViewpointTag;
import com.cloudbroker.bcs.platform.dav.middle.entity.Whitelist;
import com.cloudbroker.bcs.platform.dav.middle.entityview.AccountListView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.WhiteListView;
import com.cloudbroker.bcs.platform.dav.middle.extservice.gold.GoldService;
import com.cloudbroker.bcs.platform.dav.middle.extservice.sms.SMSExtService;
import com.cloudbroker.bcs.platform.dav.middle.extservice.uc.UCenterService;
import com.cloudbroker.bcs.platform.dav.middle.model.CustomerCache;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerActionService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerCheckService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerManagerService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.ChatRoomService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerBrokerRelService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import com.cloudbroker.bcs.platform.dav.middle.service.NewsService;
import com.cloudbroker.bcs.platform.dav.middle.service.NoticeMsgService;
import com.cloudbroker.bcs.platform.dav.middle.service.NoticeSendService;
import com.cloudbroker.bcs.platform.dav.middle.service.PermissionService;
import com.cloudbroker.bcs.platform.dav.middle.service.SystemMessageService;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;
import com.cloudbroker.bcs.platform.dav.middle.service.ValidateCodeService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointTagService;
import com.cloudbroker.bcs.platform.dav.middle.service.WhitelistService;
import com.cloudbroker.bcs.platform.dav.middle.util.AccessTokenUtil;
import com.cloudbroker.bcs.platform.dav.middle.util.GoldTokenUtil;
import com.cloudbroker.bcs.platform.dav.middle.util.PositionStrUtil;
import com.cloudbroker.bsc.common.search.util.SearchTask;
import com.hundsun.jres.common.util.UUID;

@Service
public class UserManagerBizServiceImpl implements UserManagerBizService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserManagerBizServiceImpl.class);
    
    @Resource
    private CustomerBrokerRelService customerBrokerRelService;
    
    @Resource
    private ValidateCodeService validateCodeService;
    
    @Resource
    private CustomerService customerService;
    
    @Resource
    private BrokerService brokerService;
    
    @Resource
    private NoticeSendService noticeSendService;
    
    @Resource
    private ChatRoomService chatRoomService;
    
    @Resource
    private SMSExtService smsExtService;
    
    @Resource
    private UCenterService ucService;
    
    @Resource
    private UCenterService uCenterService;
    
    @Resource
    private NoticeMsgService noticeMsgService;
    
    @Resource
    private NewsService newsService;
    
    @Resource
    private BrokerManagerService brokerManagerService;
    
    @Resource
    private PermissionService permissionService;
    
    @Resource
    private SystemMessageService systemMessageService;
    
    @Resource
    private YunxinT2BizService yunxinT2;
    
    @Resource
    private ExtendGroupT2BizService extendGroupT2;
    
    @Resource
    private ViewpointTagService viewpointTagService;
    
    @Resource
    private TenantService tenantService;
    
    @Resource
    private WhitelistService whitelistService;
    
    @Resource
    private BrokerCheckService brokerCheckService;
    
    @Resource
    private GoldService goldService;
    
    @Resource
    private BrokerActionService brokerActionService;
    
    @Override
    public OnlinenumFormBackForm funcChatRoomOnlineNumByBroker(HSBCPSVO param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        OnlinenumFormBackForm onlinenumFormBackForm = new OnlinenumFormBackForm();
        String brokerIdStr = String.valueOf(broker_id);
        Set<String> newFansList = SessionHelper.getInstance().getNewOnlineList(brokerIdStr);
        Set<String> oldFansList = SessionHelper.getInstance().getOldOnlineList(brokerIdStr);
        newFansList.addAll(oldFansList);
        onlinenumFormBackForm.setOnline_num(newFansList.size());
        /*增加是否显示在线用户开关和阈值*/
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ChatRoomErr.NO_SUCH_CHAT_ROOM,
                    OnlinenumFormBackForm.class);
        }
        onlinenumFormBackForm.setShow_threshold(ValueUtil.getIntObj(chatRoom.getShow_person_num_threshold(),
                ConfigValues.ONLINE_NUM_SHOW_THRESHOLD));
        onlinenumFormBackForm.setShow_flag(ValueUtil.getIntObj(chatRoom.getShow_person_num_flag(),
                ConfigValues.ONLINE_NUM_SHOW_FLAG));
        
        return VOUtil.setSuccessResult(onlinenumFormBackForm);
    }
    
    @Override
    public RegisternumFormBackForm funcAccountRegisternum(HSBCPSVO param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        CustomerBrokerRel queryparam = new CustomerBrokerRel();
        queryparam.setBroker_id(broker_id);
        Integer count = customerBrokerRelService.count(queryparam);
        RegisternumFormBackForm retMap = new RegisternumFormBackForm();
        retMap.setRegister_num(count);
        return VOUtil.setSuccessResult(retMap);
    }
    
    @Override
    public QueryAccountListFormBackForm funcAccountList(QueryAccountListForm param) {
        if (StringUtil.isEmpty(param.getPage_no())) {
            param.setPage_no("1");
        }
        if (StringUtil.isEmpty(param.getPage_count())) {
            param.setPage_count(String.valueOf(ConfigValues.getRequestNum()));
        }
        Broker broker = HSBCPSBizDataContext.getBroker();
        Map<String, Object> queryparam = new HashMap<String, Object>();
        queryparam.put("broker_id", broker.getBroker_id());
        queryparam.put("keyword", param.getKeyword());
        queryparam.put("block_flag", param.getBlock_flag());
        queryparam.put("page_no",
                (ValueUtil.getInt(param.getPage_no()) - 1) * ValueUtil.getInt(param.getPage_count()));
        queryparam.put("page_size", ValueUtil.getInt(param.getPage_count()));
        
        List<AccountListView> list = customerBrokerRelService.getAccountList(queryparam);
        // 获取记录总数
        Integer count = customerBrokerRelService.getQueryCount(queryparam);
        QueryAccountListFormBackForm resMap = new QueryAccountListFormBackForm();
        resMap.setPage_no(Integer.parseInt(param.getPage_no()));
        resMap.setRecord_count(count);
        resMap.newDataList().addAll(list);
        return VOUtil.setSuccessResult(resMap);
    }
    
    @Override
    public WhiteAccountListFormBackForm funcWhiteList(PageVO param) {
        Broker broker = HSBCPSBizDataContext.getBroker();
        Integer pageNo = ValueUtil.getInt(param.getPage_no(), 1);
        Integer pageSize = ValueUtil.getInt(param.getPage_count(), ConfigValues.getRequestNum());
        
        List<WhiteListView> list = whitelistService.queryByBrokerIdPage(broker.getBroker_id(), (pageNo - 1)
                * pageSize, pageSize);
        
        // 获取记录总数
        Integer count = whitelistService.countByBrokerId(broker.getBroker_id());
        WhiteAccountListFormBackForm resMap = new WhiteAccountListFormBackForm();
        List<WhiteAccountListForm> result = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (WhiteListView whiteList : list) {
                WhiteAccountListForm whiteAccountList = new WhiteAccountListForm();
                whiteAccountList.setMobile(whiteList.getMobile());
                whiteAccountList.setCustomer_name(whiteList.getName());
                result.add(whiteAccountList);
            }
            resMap.setCreate_time(DateTimeUtil.toString(list.get(0).getCreate_time(),
                    DateTimeUtil.FORMAT_YYYYMMDDHHMMSS));
        }
        resMap.setPage_no(Integer.parseInt(param.getPage_no()));
        resMap.setRecord_count(count);
        resMap.newDataList().addAll(result);
        return VOUtil.setSuccessResult(resMap);
    }
    
    @Override
    public CustomerIdFormBackForm funcAccountDetail(CustomerIdForm param) {
        Broker broker = HSBCPSBizDataContext.getBroker();
        String customer_id = param.getCustomer_id();
        Customer customer = customerService.get(customer_id);
        if (null == customer) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, CustomerIdFormBackForm.class);
        }
        
        CustomerBrokerRel customerBrokerRel = customerBrokerRelService.getByBrokerIdAndCustomerId(
                broker.getBroker_id(), Long.valueOf(customer_id));
        if (null == customerBrokerRel) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, CustomerIdFormBackForm.class);
        }
        CustomerIdFormBackForm resMap = new CustomerIdFormBackForm();
        resMap.setCustomer_name(customer.getCustomer_name());
        resMap.setSex(customer.getSex());
        resMap.setAge(String.valueOf(customer.getAge()));
        resMap.setMobile(customer.getMobile());
        resMap.setEmail(customer.getEmail());
        resMap.setQq(customer.getQq_open_id());
        resMap.setCustomer_avatar(customer.getAvatar());
        resMap.setCountry_name(customer.getCountry_name());
        resMap.setProvince_name(customer.getProvince_name());
        resMap.setCity_name(customer.getCity_name());
        resMap.setProfile(customer.getProfile());
        resMap.setStatus(customer.getStatus());
        resMap.setCreate_time(DateTimeUtil.toString(customer.getCreate_time()));
        resMap.setReward_num(customerBrokerRel.getReward_num());
        resMap.setReward_amount(customerBrokerRel.getReward_amount());
        resMap.setQuestion_num(customerBrokerRel.getQuestion_num());
        resMap.setGag_flag(customerBrokerRel.getGag_flag());
        resMap.setOnline_flag(customerBrokerRel.getOnline_flag());
        return VOUtil.setSuccessResult(resMap);
    }
    
    @Override
    public SendSMSBackForm funcAccountSendsms(SendSMSForm param) {
        VerifySource verify_source = EnumUtil.valOf(param.getVerify_source(), VerifySource.class);
        String mobile_tel = "";
        String broker_key = "";
        switch (verify_source) {
            case DAV_REGISTER:
                mobile_tel = param.getMobile();
                Broker brokerbyMobile = brokerService.getByMobile(mobile_tel);
                if (brokerbyMobile != null) {
                    return VOUtil.genErrorResult(ClientErr.MOBILE_REGISTERED, SendSMSBackForm.class);
                }
                break;
            case FANS_LOGIN:
                broker_key = param.getBroker_key();
                if (StringUtil.isBlank(broker_key)) {
                    return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, SendSMSBackForm.class);
                }
                Broker broker = brokerService.getByKey(broker_key);
                if (broker == null) {
                    return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, SendSMSBackForm.class);
                }
                HSBCPSBizDataContext.setTenantId(broker.getTenant_id());
                mobile_tel = param.getMobile();
                break;
            case FANS_LOGIN_BY_TENANT:
                String tenant_key = param.getTenant_key();
                if (StringUtil.isBlank(tenant_key)) {
                    return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, SendSMSBackForm.class);
                }
                Tenant tenant = tenantService.getByKey(tenant_key);
                if (tenant == null) {
                    return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, SendSMSBackForm.class);
                }
                HSBCPSBizDataContext.setTenantId(tenant.getTenant_id());
                mobile_tel = param.getMobile();
                break;
            case RESET_PASSWORD:
                mobile_tel = param.getMobile();
                BrokerManager bm = brokerManagerService.getByMobile(mobile_tel);
                if (bm == null) {
                    return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, SendSMSBackForm.class);
                }
                HSBCPSBizDataContext.setTenantId(bm.getTenant_id());
                break;
            case CHANGE_PASSWORD:
                Long managerId = HSBCPSBizDataContext.getClientIdNoException();
                BrokerManager manager = brokerManagerService.get(String.valueOf(managerId));
                if (null == manager) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.NOT_LOGGED, SendSMSBackForm.class);
                }
                HSBCPSBizDataContext.setTenantId(manager.getTenant_id());
                mobile_tel = manager.getMobile();
                break;
            case FANS_RESET_PASSWORD:
                mobile_tel = param.getMobile();
                Customer customer = customerService.getByMobile(mobile_tel);
                if (customer == null) {
                    return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, SendSMSBackForm.class);
                }
                HSBCPSBizDataContext.setTenantId(customer.getTenant_id());
                break;
            default:
                break;
        }
        if (StringUtil.isEmpty(mobile_tel)) {
            return VOUtil.genErrorResult(HSBCSACTIVITYErr.MOBILE_ISNULL_OR_ERROR, SendSMSBackForm.class);
        }
        SessionHelper sessionHelper = SessionHelper.getInstance();
        CacheHelper cacheHelper = CacheHelper.getInstance();
        String sendVerifyKey = sessionHelper.getSendVerifyKey(mobile_tel,
                ValueUtil.getString(verify_source.getVal()));
        if (cacheHelper.exists(sendVerifyKey)) {
            return VOUtil.genErrorResult(CommonErr.SEND_MESSAGE_FREQUENTLY, SendSMSBackForm.class);
        }
        String dailySendVerifyCountKey = sessionHelper.getDailySendVerifyCountKey(mobile_tel + broker_key);
        int sendVerifyCount = ValueUtil.getInt(cacheHelper.get(dailySendVerifyCountKey), 0);
        if (sendVerifyCount >= ConfigValues.getVerifyCodeRetryTimes()) {
            return VOUtil.genErrorResult(CommonErr.SEND_MESSAGE_TO_MAX, SendSMSBackForm.class);
        }
        
        String auth_check_code = RandomUtil.genNumericRandomString(ConfigValues.getVerifyCodeLength());
        
        if (VerifySource.RESET_PASSWORD.getVal() == param.getVerify_source()
                || VerifySource.CHANGE_PASSWORD.getVal() == param.getVerify_source()
                || VerifySource.FANS_RESET_PASSWORD.getVal() == param.getVerify_source()) {
            FuncAuthCodeForm form = new FuncAuthCodeForm();
            form.setLogin_account(mobile_tel);
            if (VerifySource.FANS_RESET_PASSWORD.getVal() == param.getVerify_source()) {
                form.setUser_type("3");
                form.setTenant_id(HSBCPSBizDataContext.getTenantId());
            } else {
                form.setUser_type("2");
            }
            AuthCodeBackVo vo = ucService.funcAuthCodeGet(form);
            logger.debug("uc-> api: error_on->" + vo.getError_no() + " error_info->" + vo.getError_info());
            if (VOUtil.isSuccess(vo)) {
                auth_check_code = vo.getAuth_code();
            } else {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.SMS_SEND_FAIL, SendSMSBackForm.class);
            }
        }
        
        String verifyMsgContent = ConfigValues.ClientMessage.getSendLoginVerifyCodeMessage(auth_check_code);
        // 发送短信
        if (smsExtService.sendMessage(mobile_tel, verifyMsgContent) == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.SMS_SEND_FAIL, SendSMSBackForm.class);
        }
        String mobileVerifyKey = sessionHelper.getMobileVerifyKey(mobile_tel,
                ValueUtil.getString(verify_source.getVal()));
        sessionHelper
                .setInfoForSession(mobileVerifyKey, auth_check_code, ConfigValues.getMobileVerifyCodeTimeout());
        int smsSendCountDown = ConfigValues.getSmsSendCountDown();
        sessionHelper.setInfoForSession(sendVerifyKey, System.currentTimeMillis() + "", smsSendCountDown);
        sessionHelper.setInfoForSession(dailySendVerifyCountKey, sendVerifyCount + 1 + "", SysContants.DAY_MILLIS);
        SendSMSBackForm map = new SendSMSBackForm();
        map.setDown_second(smsSendCountDown);
        return VOUtil.setSuccessResult(map);
    }
    
    @Override
    public HSBCPSBackVO funcAccountChangePassword(ChangePasswordForm param) {
        Long client_id = HSBCPSBizDataContext.getClientIdNoException();
        String new_password = param.getNew_password();
        String verify_code = param.getVerify_code();
        //修改用户中心密码
        if (ConfigValues.IsUserCenter()) {
            FuncPasswordResetForm form = new FuncPasswordResetForm();
            form.setLogin_account(HSBCPSBizDataContext.getBroker().getMobile());
            form.setAuth_code(verify_code);
            form.setAuth_password(MD5Util.encrypt(new_password));
            form.setUser_type("2");
            form.setUser_token(param.getUser_token());
            HSBCPSBackVO vo = uCenterService.funcPasswordReset(form);
            if (!VOUtil.isSuccess(vo)) {
                return VOUtil.genErrorResult(BasicErrorCodes.USER_CENTER_INTERFACE_ERR, HSBCPSBackVO.class);
            }
        }
        
        BrokerManager manager = brokerManagerService.get(String.valueOf(client_id));
        if (null == manager) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, HSBCPSBackVO.class);
        }
        Broker broker = brokerService.get(String.valueOf(manager.getBroker_id()));
        if (null == broker) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, HSBCPSBackVO.class);
        }
        if (!validateCodeService.checkCodeTime(manager.getMobile(), "", VerifySource.CHANGE_PASSWORD.getVal())) {
            return VOUtil.genErrorResultVo(CommonErr.VALIDAET_CODE_TIMT_OUT);
        }
        if (!validateCodeService.checkCode(verify_code, manager.getMobile(), "",
                VerifySource.CHANGE_PASSWORD.getVal())) {
            return VOUtil.genErrorResultVo(CommonErr.VERIFY_CODE_WRONG);
        }
        if (!MD5Util.encrypt(param.getOld_password()).equals(manager.getPassword())) {
            return VOUtil.genErrorResultVo(ClientErr.CLIENT_PWD_ERR);
        }
        manager.setPassword(MD5Util.encrypt(new_password));
        brokerManagerService.update(manager);
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public HSBCPSBackVO funcAccountResetPassword(ResetPasswordForm param) {
        String mobile_tel = param.getMobile();
        String new_password = param.getNew_password();
        String verify_code = param.getVerify_code();
        
        //修改用户中心密码
        if (ConfigValues.IsUserCenter()) {
            FuncPasswordResetForm form = new FuncPasswordResetForm();
            form.setLogin_account(mobile_tel);
            form.setAuth_code(verify_code);
            form.setAuth_password(MD5Util.encrypt(new_password));
            form.setUser_type("2");
            form.setUser_token(param.getUser_token());
            HSBCPSBackVO vo = uCenterService.funcPasswordReset(form);
            if (!VOUtil.isSuccess(vo)) {
                return VOUtil.genErrorResult(BasicErrorCodes.USER_CENTER_INTERFACE_ERR, HSBCPSBackVO.class);
            }
        }
        
        BrokerManager manager = brokerManagerService.getByMobile(mobile_tel);
        if (null == manager) {
            return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
        }
        Broker broker = brokerService.get(String.valueOf(manager.getBroker_id()));
        if (null == broker) {
            return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
        }
        if (!validateCodeService.checkCodeTime(manager.getMobile(), "", VerifySource.RESET_PASSWORD.getVal())) {
            SessionHelper sessionHelper = SessionHelper.getInstance();
            CacheHelper cacheHelper = CacheHelper.getInstance();
            String mobileVerifyKey = sessionHelper.getSendVerifyKeyConfig(mobile_tel,
                    ValueUtil.getString(VerifySource.RESET_PASSWORD.getVal()));
            long today = System.currentTimeMillis();
            String time = cacheHelper.get(mobileVerifyKey);
            Map<String, Object> cifMap = new HashMap<>();
            int outTime = ConfigValues.getMobileVerifyCodeTimeout();
            long time_out = 120000;
            if (!StringUtil.isEmpty(time)) {
                time_out = today - Long.parseLong(time);
            }
            cifMap.put("time_out", outTime - time_out / 1000);
            return VOUtil.genErrorResultVo(CommonErr.VALIDAET_CODE_TIMT_OUT);
        }
        if (!validateCodeService.checkCode(verify_code, manager.getMobile(), "",
                VerifySource.RESET_PASSWORD.getVal())) {
            return VOUtil.genErrorResultVo(CommonErr.VERIFY_CODE_WRONG);
        }
        
        manager.setPassword(MD5Util.encrypt(new_password));
        brokerManagerService.update(manager);
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public ImgVerifyFormBackForm funcAccountImgverify(ImgVerifyForm param) {
        String auth_check_code = RandomUtil.genNumericRandomString(4);
        CacheHelper.getInstance().set(CacheKeys.PIC_CAPTCHA + param.getGuid(), auth_check_code,
                ConfigValues.getImgVerifyCodeTimeout());
        ImgVerifyFormBackForm resMap = new ImgVerifyFormBackForm();
        resMap.setVerify_code(auth_check_code);
        return VOUtil.setSuccessResult(resMap);
    }
    
    @Override
    public LoginFormBackForm funcBrokerRegister(BrokerRegForm form) {
        String verify_code = form.getVerify_code();
        if (!StringUtil.isBlank(verify_code)) {
            if (!validateCodeService.checkCode(verify_code, form.getMobile(), "",
                    VerifySource.DAV_REGISTER.getVal())) {
                return VOUtil.genErrorResult(CommonErr.VERIFY_CODE_WRONG, LoginFormBackForm.class);
            }
        }
        Integer tenantId = null;
        
        //有组织架构的投顾注册租户需要填写组织机构相关信息
        String branch_no = form.getBranch_no();
        if (StringUtil.isBlank(branch_no)) {
            if (!StringUtil.isBlank(form.getTenant_id())) {
                try {
                    String tenantIdStr = form.getTenant_id();
                    tenantId = Integer.parseInt(tenantIdStr.substring(0, tenantIdStr.length() - 4));
                    String keyStart = tenantIdStr.substring(tenantIdStr.length() - 4);
                    Tenant tenant = tenantService.get(String.valueOf(tenantId));
                    if (!tenant.getTenant_key().startsWith(keyStart)) {
                        return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, LoginFormBackForm.class);
                    }
                } catch (Exception e) {
                    return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, LoginFormBackForm.class);
                }
            } else {
                if (String.valueOf(WxAccountType.PERSONAL.getVal()).equals(form.getWx_account())) {
                    tenantId = this.getPersinalTenantId(form.getApplicant_name());
                    branch_no = String.valueOf(tenantId);
                } else {
                    //机构用户必须填写租户ID
                    return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, LoginFormBackForm.class);
                }
            }
        } else {
            if (!StringUtil.isBlank(form.getTenant_id())) {
                try {
                    tenantId = ValueUtil.getInt(form.getTenant_id());
                    Tenant tenant = tenantService.get(form.getTenant_id());
                    if (tenant == null) {
                        return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, LoginFormBackForm.class);
                    }
                } catch (Exception e) {
                    return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, LoginFormBackForm.class);
                }
            } else {
                Tenant tenantTemp = tenantService.getByBranchNo(branch_no);
                if (tenantTemp == null) {
                    return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, LoginFormBackForm.class);
                }
                tenantId = tenantTemp.getTenant_id();
            }
        }
        
        String broker_name = StringUtil.isEmpty(form.getBroker_name()) ? form.getApplicant_name() : form
                .getBroker_name();
        if (checkUserName(broker_name)) {
            return VOUtil.genErrorResult(ClientErr.USER_NAME_EXSIT, LoginFormBackForm.class);
        }
        //查询用户中心是否注册，已注册直接返回手机号已注册，没有注册先去用户中心注册
        Long user_id = null;
        if (ConfigValues.IsUserCenter()) {
            user_id = readAndRegisterUserId(form.getBroker_name(), form.getMobile(), form.getPassword(), tenantId,
                    branch_no);
            if (user_id.equals(-1L)) {
                return VOUtil.genErrorResult(ClientErr.MOBILE_REGISTERED, LoginFormBackForm.class);
            } else if (user_id.equals(0L)) {
                return VOUtil.genErrorResult(BasicErrorCodes.USER_CENTER_INTERFACE_ERR, LoginFormBackForm.class);
            } else if (user_id.equals(-2L)) {
                return VOUtil.genErrorResult(ClientErr.USER_NAME_EXSIT, LoginFormBackForm.class);
            }
            
        } else {
            BrokerManager brokerManager = brokerManagerService.getByMobile(form.getMobile());
            if (brokerManager != null) {
                return VOUtil.genErrorResult(ClientErr.MOBILE_REGISTERED, LoginFormBackForm.class);
            }
        }
        
        Broker broker = new Broker();
        //设置基础信息
        broker.setWx_account(form.getWx_account());
        broker.setBusiness_licence(form.getBusiness_licence());
        broker.setCertificate_type(form.getCertificate_type());
        broker.setCertificate_id(form.getCertificate_id());
        broker.setOwn_organ(form.getOwn_organ());
        broker.setJob_title(form.getJob_title());
        broker.setProvince_name(form.getProvince_name());
        broker.setCity_name(form.getCity_name());
        broker.setSpeciality(form.getSpeciality());
        broker.setProfile(form.getProfile());
        broker.setFr_code(form.getFr_code());
        
        broker.setEmail(form.getEmail());
        broker.setMobile(form.getMobile());
        broker.setBroker_name(broker_name);
        broker.setBroker_status(String.valueOf(CustomerStatus.NOMAL.getVal()));
        String pwd = MD5Util.encrypt(form.getPassword());
        broker.setPassword(pwd);
        broker.setWx_public_account(form.getWx_public_account());
        broker.setBroker_key(UUID.randomUUID().toString());
        broker.setCreate_date(new Date());
        broker.setApplicant_name(form.getApplicant_name());
        broker.setCompany(form.getCompany_name());
        broker.setAccount_holder(form.getAccount_holder());
        broker.setBank_account(form.getBank_account());
        broker.setBank_name(form.getBank_name());
        broker.setFans_num(StringUtil.isEmpty(form.getFans_num()) ? null : Integer.valueOf(form.getFans_num()));
        broker.setId_card_img_back(form.getIdcard_img_back());
        broker.setId_card_img_front(form.getIdcard_img_front());
        broker.setId_no(form.getId_no());
        broker.setWeibo_id(form.getWeibo_id());
        broker.setReply_status(String.valueOf(ApplyStatus.UNDER_REVIEW.getVal()));
        
        broker.setTenant_id(tenantId);
        brokerService.save(broker);
        
        //有组织架构的投顾注册需要审核
        if (!StringUtil.isBlank(branch_no)) {
            BrokerCheck brokerCheck = new BrokerCheck();
            brokerCheck.setBroker_id(broker.getBroker_id());
            brokerCheck.setCheck_manager(1);
            brokerCheck.setCheck_result("0");
            brokerCheck.setTenant_id(tenantId);
            brokerCheckService.save(brokerCheck);
        }
        
        BrokerManager manager = new BrokerManager();
        manager.setName(broker.getBroker_name());
        manager.setMobile(form.getMobile());
        manager.setPassword(pwd);
        manager.setBroker_flag(1);
        manager.setBroker_id(broker.getBroker_id());
        manager.setCreate_time(new Date());
        manager.setTenant_id(tenantId);
        manager.setDelete_flag(0);
        manager.setUser_id(user_id);
        brokerManagerService.save(manager);
        
        //云信注册
        brokerManagerService.yunxinRoomReg(broker, manager, true);
        //保存默认标签
        viewpointTagService.saveTagForBroker(broker);
        
        ExtendGroupBuildDefaultForm defaultForm = new ExtendGroupBuildDefaultForm();
        defaultForm.setBroker_id(String.valueOf(broker.getBroker_id()));
        extendGroupT2.funcExtendGroupBuildDefault(defaultForm);
        LoginFormBackForm result = this.setLoginReturnForm(manager, broker, BrokerLoginType.APP, null, null);
        return VOUtil.setSuccessResult(result);
    }
    
    private Long readAndRegisterUserId(String brokerName, String mobile, String password, Integer tenantId,
            String branchNo) {
        FuncLoginForm param = new FuncLoginForm();
        param.setLogin_account(mobile);
        param.setUser_type("2");
        CheckRegisterBackVo vo = uCenterService.funcCheckRegister(param);
        if (VOUtil.isSuccess(vo)) {
            String is_register = vo.getIs_register();
            if ("1".equals(is_register)) {
                logger.error("手机号{}已注册！", mobile);
                return -1L;
            } else {
                //注册用户中心
                FuncRegisterForm rform = new FuncRegisterForm();
                rform.setLogin_account(mobile);
                rform.setAuth_password(MD5Util.encrypt(password));
                rform.setUser_type("2");
                rform.setTenant_id(tenantId);
                rform.setAlias_name(brokerName);
                rform.setRegister_flag("1");
                rform.setBranch_no(branchNo);
                rform.setMobile(mobile);
                UIDBackVo bvo = uCenterService.funcRegister(rform);
                if (VOUtil.isSuccess(bvo)) {
                    //更新user_id到manager表
                    return bvo.getUser_id();
                } else {
                    logger.error("手机号{}注册用户中心失败！", mobile);
                    if ("10055".equals(bvo.getError_no())) {
                        return -2L;
                    }
                    return 0L;
                }
            }
        }
        logger.error("手机号{}校验用户是否注册失败！", mobile);
        return 0L;
    }
    
    private Integer getPersinalTenantId(String name) {
        Integer maxTenantId = tenantService.getMax();
        if (maxTenantId == null || maxTenantId < 999999) {
            maxTenantId = 999999;
        } else {
            maxTenantId++;
        }
        Tenant tenant = new Tenant();
        tenant.setTenant_id(maxTenantId);
        tenant.setTenant_key(UUID.randomUUID().toString());
        tenant.setCompany_id(String.valueOf(maxTenantId));
        tenant.setBranch_no(String.valueOf(maxTenantId));
        tenant.setName(name);
        tenant.setViewpoint_public_flag(String.valueOf(ViewpointPublicType.NO_PUBLIC.getVal()));
        tenantService.save(tenant);
        return maxTenantId;
    }
    
    //    private Integer getTenantIdByCompanyId(Integer companyId) {
    //        Integer tenantId = SessionHelper.getInstance().getTenantIdByCompanyId(companyId);
    //        if (tenantId != null) {
    //            return tenantId;
    //        }
    //        Tenant tenant = tenantService.getByCompanyId(companyId);
    //        if (tenant == null) {
    //            tenant = new Tenant();
    //            tenant.setCreate_date(new Date());
    //            tenant.setTenant_key(UUID.randomUUID().toString());
    //            tenant.setBranch_no(String.valueOf(companyId));
    //            tenant.setCompany_id(String.valueOf(companyId));
    //            tenant.setBranch_grade("1");
    //            tenantService.save(tenant);
    //        }
    //        tenantId = tenant.getTenant_id();
    //        SessionHelper.getInstance().setTenantCompanyIdRel(tenantId, companyId);
    //        return tenantId;
    //    }
    
    @Override
    public BatchImportBrokerBackForm funcBatchImportBroker(BatchImportBrokerListForm form) {
        List<BatchImportBrokerForm> batchImportBrokerForms = form.getDataList();
        Integer tenant_id = null;
        String password = "7ea795072786a3263957be61afa6126f";
        int i = 0;
        for (BatchImportBrokerForm temp : batchImportBrokerForms) {
            if (StringUtil.isBlank(temp.getMobile())) {
                continue;
            } else {
                String mobile = temp.getMobile().trim();
                BigDecimal bd = new BigDecimal(mobile);
                mobile = bd.toPlainString();
                temp.setMobile(mobile);
            }
            
            Tenant tenant = null;
            String branchNo = "";
            /*不符合创建条件，直接下一条*/
            if (!chechNecsseryInfo(temp)) {
                continue;
            }
            
            if (tenant_id == null && StringUtil.isBlank(temp.getTenant_id())) {
                /*創建新的租戶*/
                if (!StringUtil.isBlank(temp.getOwn_organ())) {
                    tenant = tenantService.getByBranchName(temp.getOwn_organ());
                    if (tenant != null) {
                        tenant_id = tenant.getTenant_id();
                    }
                }
                
            } else if (!StringUtil.isBlank(temp.getTenant_id())) {
                tenant_id = Integer.valueOf(temp.getTenant_id().trim());
                tenant = tenantService.get(temp.getTenant_id().trim());
                if (tenant == null) {
                    tenant_id = null;
                } else {
                    branchNo = tenant.getBranch_no();
                }
            }
            if (tenant_id == null) {
                //有组织架构的投顾注册需要审核
                tenant = new Tenant();
                tenant.setCreate_date(new Date());
                tenant.setTenant_key(UUID.randomUUID().toString());
                tenant.setBranch_name(temp.getOwn_organ());
                tenant.setBranch_no(temp.getCertificate_id());
                tenant.setBranch_no("1");
                tenantService.save(tenant);
                /*tenant = tenantService.getByKey(tenant.getTenant_key());*/
                tenant_id = tenant.getTenant_id();
                branchNo = tenant.getBranch_no();
            }
            Long userId = readAndRegisterUserId(temp.getBroker_name(), temp.getMobile(), password, tenant_id,
                    branchNo);
            /*已注册或注册失败*/
            if (userId.equals(-1L) || userId.equals(0L) || userId.equals(-2L)) {
                continue;
            }
            Broker broker = new Broker();
            broker.setBroker_name(temp.getBroker_name());
            broker.setMobile(temp.getMobile());
            broker.setId_no(temp.getId_no() == null ? "" : temp.getId_no());
            broker.setWx_account(temp.getWx_account());
            broker.setWx_public_account(temp.getWx_public_account());
            broker.setEmail(temp.getEmail());
            broker.setProfile(temp.getProfile());
            broker.setService_tel(temp.getSpeciality());
            broker.setBroker_status(String.valueOf(CustomerStatus.NOMAL.getVal()));
            //String pwd = MD5Util.encrypt("7ea795072786a3263957be61afa6126f");//aB123456
            String pwd = MD5Util.encrypt(password);
            broker.setPassword(pwd);
            broker.setBroker_key(UUID.randomUUID().toString());
            
            broker.setCreate_date(new Date());
            broker.setCompany(temp.getCompany_name());
            broker.setApplicant_name(temp.getBroker_name());
            broker.setId_card_img_back("");
            broker.setId_card_img_front("");
            
            broker.setReply_status(String.valueOf(ApplyStatus.UNDER_REVIEW.getVal()));
            broker.setTenant_id(tenant_id);
            brokerService.save(broker);
            BrokerStatusChangeForm brokerStatusChangeForm = new BrokerStatusChangeForm();
            brokerStatusChangeForm.setBroker_id(String.valueOf(broker.getBroker_id()));
            brokerStatusChangeForm.setTenant_id(String.valueOf(tenant_id));
            brokerStatusChangeForm.setBroker_type("0");
            funcBrokerChangeStatus(brokerStatusChangeForm);
            BrokerManager manager = new BrokerManager();
            manager.setName(broker.getBroker_name());
            manager.setMobile(temp.getMobile());
            manager.setPassword(pwd);
            manager.setBroker_flag(1);
            manager.setBroker_id(broker.getBroker_id());
            manager.setCreate_time(new Date());
            manager.setTenant_id(tenant_id);
            manager.setDelete_flag(0);
            manager.setUser_id(userId);
            brokerManagerService.save(manager);
            
            //云信注册
            brokerManagerService.yunxinRoomReg(broker, manager, true);
            //保存默认标签
            viewpointTagService.saveTagForBroker(broker);
            //注册金币系统
            GoldRegiste(broker);
            
            ExtendGroupBuildDefaultForm defaultForm = new ExtendGroupBuildDefaultForm();
            defaultForm.setBroker_id(String.valueOf(broker.getBroker_id()));
            extendGroupT2.funcExtendGroupBuildDefault(defaultForm);
            i++;
        }
        BatchImportBrokerBackForm batchImportBrokerBackForm = new BatchImportBrokerBackForm();
        batchImportBrokerBackForm.setTenant_id(String.valueOf(tenant_id));
        batchImportBrokerBackForm.setNum(i);
        return VOUtil.setSuccessResult(batchImportBrokerBackForm);
    }
    
    private void GoldRegiste(Broker broker) {
        RegisteForm param = new RegisteForm();
        param.setMobile(broker.getMobile());
        param.setUser_token(GoldTokenUtil.getGoldToken());
        param.setUser_id(broker.getBroker_key());
        param.setTenant_id(String.valueOf(broker.getTenant_id()));
        goldService.goldRegiste(param);
    }
    
    @Override
    public BrokerRegFormBackForm funcBrokerRegisterCheck(BrokerRegCheckForm form) {
        String account = ConfigValues.getRegCheckAccount();
        String pwd = ConfigValues.getRegCheckPassword();
        BrokerRegFormBackForm backForm = new BrokerRegFormBackForm();
        backForm.setOss_prefix(ConfigValues.getInterfaceOssAddr());
        if (account.equals(form.getBroker_account())
                && MD5Util.encrypt(pwd).toLowerCase().equals(form.getPassword())) {
            return VOUtil.setSuccessResult(backForm);
        }
        return VOUtil.genErrorResult(ClientErr.CLIENT_NAME_PWD_ERR, BrokerRegFormBackForm.class);
    }
    
    @Override
    public LoginFormBackForm funcAccountLogin(LoginForm form) {
        String mobile_tel = form.getMobile();
        String auth_password = form.getPassword();
        String verify_code = form.getVerify_code();
        String login_ip = form.getLogin_ip();
        if (!isSuperVerifyCodePassed(verify_code)) {
            // 获取图片验证码缓存
            String pic_vc = CacheHelper.getInstance().get(CacheKeys.PIC_CAPTCHA + form.getVerify_base());
            if (!verify_code.equals(pic_vc)) {
                saveBrokerLoginInfo(LoginErrType.CODE_WRONG.getDescription(), false, mobile_tel, login_ip, null);
                return VOUtil.genErrorResult(CommonErr.VERIFY_CODE_WRONG, LoginFormBackForm.class);
            }
            CacheHelper.getInstance().destroy(CacheKeys.PIC_CAPTCHA + form.getVerify_base());
        }
        //接入用户中心登录,先登录用户中心，如果没有则返回失败，如果有则查询是否有工作室记录，如果没有则创建一个新投顾，有则登录工作室
        FuncLoginForm param = new FuncLoginForm();
        param.setLogin_account(mobile_tel);
        param.setAuth_password(MD5Util.encrypt(auth_password));
        param.setUser_type("2");
        UIDBackVo vo = uCenterService.funcLogin(param);
        if (VOUtil.isSuccess(vo)) {
            String user_status = vo.getUser_status();
            if (!StringUtil.isBlank(user_status)) {
                if (!"0".equals(user_status)) {
                    saveBrokerLoginInfo(LoginErrType.STATUS_ERR.getDescription(), false, mobile_tel, login_ip, null);
                    return VOUtil.genErrorResult(ClientErr.USER_ACCOUNT_STATUS_ERR, LoginFormBackForm.class);
                }
            }
        } else {
            saveBrokerLoginInfo(LoginErrType.PWD_ERR.getDescription(), false, mobile_tel, login_ip, null);
            return VOUtil.genErrorResult(ClientErr.CLIENT_NAME_PWD_ERR, LoginFormBackForm.class);
        }
        String ucUserToken = vo.getUser_token();
        Long ucId = vo.getUser_id();
        BrokerManager manager = brokerManagerService.getManagerByUcId(form.getMobile(),
                MD5Util.encrypt(auth_password), ucUserToken, ucId);
        //存在投顾,需要校验此投顾是否删除
        Broker broker = brokerService.get(String.valueOf(manager.getBroker_id()));
        if (null == broker) {
            saveBrokerLoginInfo(LoginErrType.CLIENT_ERR.getDescription(), false, mobile_tel, login_ip, manager);
            return VOUtil.genErrorResult(ClientErr.CLIENT_NAME_PWD_ERR, LoginFormBackForm.class);
        }
        
        HSBCPSBizDataContext.setTenantId(manager.getTenant_id());
        //查询是否审核通过
        if (!String.valueOf(CustomerStatus.NOMAL.getVal()).equals(broker.getBroker_status())
                || !String.valueOf(ApplyStatus.PASS.getVal()).equals(broker.getReply_status())) {
            saveBrokerLoginInfo(LoginErrType.STATUS_ERR.getDescription(), false, mobile_tel, login_ip, manager);
            return VOUtil.genErrorResult(ClientErr.CLIENT_NAME_PWD_ERR, LoginFormBackForm.class);
        }
        LoginFormBackForm result = setLoginReturnForm(manager, broker,
                EnumUtil.valOf(form.getLogin_type(), BrokerLoginType.class), ucUserToken, ucId);
        saveBrokerLoginInfo(LoginErrType.SUCCESS.getDescription(), true, mobile_tel, login_ip, manager);
        return VOUtil.setSuccessResult(result);
    }
    
    /**
     * 保存投顾登录信息
     * @param mobile_tel
     */
    private void saveBrokerLoginInfo(String error_info, boolean error_no, String mobile_tel, String login_ip,
            BrokerManager manager) {
        if (null != manager) {
            saveLoginInfo(error_info, error_no, login_ip, manager);
        } else {
            manager = brokerManagerService.getByMobile(mobile_tel);
            if (null != manager) {
                saveLoginInfo(error_info, error_no, login_ip, manager);
            }
        }
    }
    
    private void saveLoginInfo(String error_info, boolean error_no, String login_ip, BrokerManager manager) {
        BrokerAction action = new BrokerAction();
        action.setUser_id(manager.getUser_id());
        action.setBroker_id(manager.getBroker_id());
        action.setTenant_id(manager.getTenant_id());
        action.setMobile(manager.getMobile());
        action.setAction_ip(login_ip);
        action.setAction_type(String.valueOf(CommonType.TRUE.getVal()));
        action.setCreate_time(new Date());
        action.setPosition_str(PositionStrUtil.getPositionStr());
        if (error_no) {
            action.setAction_result(String.valueOf(CommonType.TRUE.getVal()));
        } else {
            action.setAction_result(String.valueOf(CommonType.FALSE.getVal()));
        }
        action.setAction_remark(error_info);
        brokerActionService.save(action);
    }
    
    /**
     * 是否超级验证码
     *
     * @param auth_check_code
     * @return
     */
    private boolean isSuperVerifyCodePassed(String auth_check_code) {
        return ConfigValues.getVerifyCodeSuperSwitch()
                && ConfigValues.getVerifyCodeSuperValue().equalsIgnoreCase(auth_check_code);
    }
    
    /**
     * 
     * @param manager
     * @param broker
     * @param loginType
     * @param ucUserToken 用户中心UserToken
     * @return
     */
    private LoginFormBackForm setLoginReturnForm(BrokerManager manager, Broker broker, BrokerLoginType loginType,
            String ucUserToken, Long ucId) {
        // 写会话令牌到返回结果
        LoginFormBackForm result = new LoginFormBackForm();
        result.setBroker_flag(manager.getBroker_flag());
        // 保存新的用户会话
        if (ucUserToken == null) {
            ucUserToken = saveNewBrokerSession(manager, broker, manager.getBroker_flag() != 1, result, loginType);
        } else {
            //用户中心过来的
            CustomerCache identity = brokerManagerService.createNewBrokerIdentity(broker,
                    manager.getBroker_manager_id(), manager.getUser_id(), manager.getBroker_flag() != 1, loginType);
            setPermissionsToBackForm(result, identity.getPermissions());
            SessionHelper.getInstance().renewUCUserInfo(identity, ucId);
        }
        result.setUser_token(ucUserToken);
        result.setBroker_name(broker.getBroker_name());
        result.setBroker_avatar(manager.getBroker_avatar() == null ? broker.getBroker_avatar() : manager
                .getBroker_avatar());
        result.setBroker_id(broker.getBroker_id());
        result.setYunxin_token(manager.getYunxin_token());
        result.setYunxin_acct(manager.getYunxin_acct());
        result.setBroker_key(broker.getBroker_key());
        result.setOss_prefix(ConfigValues.getInterfaceOssAddr());
        result.setManager_name(manager.getName());
        Integer roomId = chatRoomService.setYunxinRoomUrl(result, manager.getYunxin_acct(), broker.getBroker_id());
        GetChatroomAddrForm params = new GetChatroomAddrForm();
        params.setRoomid(roomId);
        params.setAccid(result.getYunxin_acct());
        GetChatroomAddrBackVo retMap = yunxinT2.getChatroomAddr(params);
        if (retMap != null) {
            result.setYunxin_broadcast_url(retMap.getAddr());
        }
        result.setYunxin_appkey(ConfigValues.getYunxinAppkey());
        result.setAccess_token(AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal()));
        /*金币叫法配置*/
        String coinsName = ConfigUtil.getTenantConfig("tenant" + ValueUtil.getString(manager.getTenant_id())).get(
                "tenant.id.coins.name", ConfigValues.COINS_NAME);
        result.setCoin_name(coinsName);
        int cclive_visible = ConfigUtil.getTenantConfig("tenant" + ValueUtil.getString(manager.getTenant_id())).get("is.cclive.visible", true) == true ? 1 : 0;
        result.setCclive_visible(cclive_visible);
        //注册金币系统
        GoldRegiste(broker);
        return result;
    }
    
    private String saveNewBrokerSession(BrokerManager manager, Broker broker, boolean isManager,
            LoginFormBackForm result, BrokerLoginType loginType) {
        Long client_id = manager.getBroker_manager_id();
        // 根据clientId 获取 客户的 access_token,获取到token 把当前的token 注销掉
        String clientIdToken = SessionHelper.getInstance().getSessionTokenByClientId(PlatformType.MANAGE,
                loginType.getVal() + client_id.toString());
        // 客户已经存在token，删除token
        if (!StringUtil.isBlank(clientIdToken)) {
            // 销毁会话令牌
            SessionHelper.getInstance().delete(clientIdToken);
        }
        CustomerCache identity = brokerManagerService.createNewBrokerIdentity(broker,
                manager.getBroker_manager_id(), manager.getUser_id(), isManager, loginType);
        Set<String> permissions = identity.getPermissions();
        setPermissionsToBackForm(result, permissions);
        //接入用户中心登录用户中心获取token
        String access_token = SessionHelper.getInstance().renewAccess_token(identity);
        // 把生成的token保存到缓存
        SessionHelper.getInstance().saveNewClientIDSession(PlatformType.MANAGE, client_id, access_token,
                broker.getTenant_id(), loginType);
        
        return access_token;
    }
    
    private void setPermissionsToBackForm(LoginFormBackForm result, Set<String> permissions) {
        if (permissions != null) {
            StringBuilder sb = new StringBuilder();
            for (String per : permissions) {
                sb.append(per);
                sb.append(',');
            }
            if (!permissions.isEmpty()) {
                sb.setLength(sb.length() - 1);
            }
            result.setPermissions(sb.toString());
        }
    }
    
    @Override
    public HSBCPSBackVO funcAccountLogout(HSBCPSVO form) {
        String access_token = form.getUser_token();
        
        //退出用户中心
        if (ConfigValues.IsUserCenter()) {
            UCForm param = new UCForm();
            param.setUser_token(access_token);
            uCenterService.funcLogout(param);
        }
        
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        String access_tokenKey = SessionHelper.getInstance().getClient_idKey(PlatformType.MANAGE,
                String.valueOf(brokerId));
        SessionHelper.getInstance().delete(access_tokenKey);
        SessionHelper.getInstance().destroySession(access_token);
        SessionHelper.getInstance().removeOnlineFromList(String.valueOf(brokerId), String.valueOf(brokerId));
        HSBCPSBizDataContext.removeCustomer();
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public NewsSaveFormBackForm funcNewsSave(NewsSaveForm param) {
        News news = new News();
        news.setTitle(param.getTitle());
        try {
            news.setTime(DateTimeUtil.toDate(param.getTime(), DateTimeUtil.FORMAT_YYYYMMDDHHMMSS));
        } catch (ParseException e) {
            try {
                news.setTime(DateTimeUtil.toDate(param.getTime(), DateTimeUtil.FORMAT_YYYYMMDD));
            } catch (ParseException e2) {
                logger.error("时间转换错误", param);
            }
        }
        int count = this.newsService.count(news);
        NewsSaveFormBackForm result = new NewsSaveFormBackForm();
        if (count > 0) {
            news = this.newsService.query(news).get(0);
            result.setNews_id(news.getNews_id());
            return VOUtil.setSuccessResult(result);
        }
        BeanUtils.copyProperties(param, news);
        news.setSource_channel("ITN");
        newsService.save(news);
        result.setNews_id(news.getNews_id());
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public NewsQueryFormBackForm funcNewsQry(NewsQueryForm param) {
        String news_id = param.getNews_id();
        News news = newsService.get(news_id);
        if (news == null) {
            return VOUtil.genErrorResult(FavoriteErr.NEWS_NOT_EXIST, NewsQueryFormBackForm.class);
        }
        NewsQueryFormBackForm resMap = new NewsQueryFormBackForm();
        resMap.setNews_id(news.getNews_id());
        resMap.setTitle(news.getTitle());
        resMap.setNews_abstract(news.getNews_abstract());
        resMap.setContent(news.getContent());
        resMap.setLink(news.getLink());
        resMap.setTime(DateTimeUtil.toString(news.getTime()));
        resMap.setMedia(news.getMedia());
        resMap.setPicture(news.getPicture());
        return VOUtil.setSuccessResult(resMap);
    }
    
    @Override
    public HSBCPSBackVO funcBrokerNoticeSave(NoticeInfoForm param) {
        Broker broker = HSBCPSBizDataContext.getBroker();
        Long broker_id = broker.getBroker_id();
        NoticeType noticeType = EnumUtil.valOf(Integer.valueOf(param.getNotice_type()), NoticeType.class);
        String notice_content = param.getNotice_content();
        if (NoticeType.ROLL.equals(noticeType)) {
            NoticeMsg nm = new NoticeMsg();
            nm.setNotice_title("滚动通知消息");
            nm.setNotice_content(notice_content);
            nm.setNotice_status(String.valueOf(NoticeSendStatus.SEND.getVal()));
            nm.setBroker_id(broker_id);
            nm.setSend_time(new Date());
            noticeMsgService.save(nm);
            return VOUtil.genSuccessBackVo();
        } else {
            if (StringUtil.isBlank(notice_content)) {
                return VOUtil.genErrorResultVo(RollingMsgErr.CONTENT_NOT_BLANK);
            }
            List<Long> customer_ids = customerBrokerRelService.getCustomerIdsByBrokerId(broker_id);
            systemMessageService.noticeFans(broker_id, customer_ids, noticeType,
                    "您有新的" + noticeType.getDescription() + "消息", notice_content);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public HSBCPSBackVO funcBrokerInfoUpdate(BrokerInfoForm param) {
        Broker c = HSBCPSBizDataContext.getBroker();
        String broker_name = param.getBroker_name();
        if (!StringUtil.isEmpty(broker_name) && !c.getBroker_name().equals(broker_name)) {
            if (checkUserName(broker_name)) {
                return VOUtil.genErrorResultVo(ClientErr.USER_NAME_EXSIT);
            }
        }
        String customer_avatar = param.getBroker_avatar();
        String customer_profile = param.getProfile();
        
        //更新用户中心信息
        FuncUserUpdateForm form = new FuncUserUpdateForm();
        form.setAvatar(customer_avatar);
        form.setAlias_name(broker_name);
        form.setUser_token(HSBCPSBizDataContext.getAccess_token());
        HSBCPSBackVO vo = uCenterService.funcUserUpdate(form);
        if (!VOUtil.isSuccess(vo)) {
            if ("10055".equals(vo.getError_no())) {
                return VOUtil.genErrorResultVo(ClientErr.USER_NAME_EXSIT);
            }
            return VOUtil.genErrorResultVo(ClientErr.USER_INFO_UPDATE_ERROR);
        }
        
        //云信更新用户名片
        if (!StringUtil.isEmpty(customer_avatar)) {
            c.setBroker_avatar(customer_avatar);
        }
        if (!StringUtil.isEmpty(customer_profile)) {
            c.setProfile(customer_profile);
        }
        if (!StringUtil.isEmpty(broker_name)) {
            c.setBroker_name(broker_name);
        }
        UserInfoForm info = new UserInfoForm();
        BrokerManager manager = brokerManagerService.getByMobile(c.getMobile());
        if (manager == null) {
            return VOUtil.genErrorResultVo(ClientErr.BROKER_NOT_FIND);
        }
        info.setAccid(manager.getYunxin_acct());
        info.setIcon(c.getBroker_avatar());
        info.setSign(c.getProfile());
        info.setName(c.getBroker_name());
        yunxinT2.updateUserInfo(info);
        /*更新一下brokermanager*/
        if (!StringUtil.isEmpty(customer_avatar)
                && (StringUtil.isEmpty(manager.getBroker_avatar()) || (!StringUtil.isEmpty(manager
                        .getBroker_avatar()) && !customer_avatar.equals(manager.getBroker_avatar())))) {
            manager.setBroker_avatar(customer_avatar);
            brokerManagerService.update(manager);
        }
        
        c.setUpdate_time(new Date());
        brokerService.update(c);
        Map<String, String> mapUpdate = new HashMap<String, String>();
        mapUpdate.put("broker_name", c.getBroker_name());
        mapUpdate.put("broker_avatar", c.getBroker_avatar());
        Map<String, String> mapQry = new HashMap<String, String>();
        mapQry.put("broker_id", "es equals " + c.getBroker_id());
        SearchTask.updateBitchTask(mapQry, mapUpdate);
        CustomerCache cache = SessionHelper.getInstance().fetchSessionIdentity(CustomerCache.class);
        if (null != cache) {
            cache.setBroker(c);
            SessionHelper.getInstance().renewIdentity(cache);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public BrokerAccountListBackForm funcBrokerAccountList(QueryAccountListForm param) {
        if (StringUtil.isEmpty(param.getSort_field())) {
            param.setSort_field("1");
        }
        if (StringUtil.isEmpty(param.getSort_type())) {
            param.setSort_type("1");
        }
        
        Integer page_no = ValueUtil.getInt(param.getPage_no(), 1);
        Integer page_size = ValueUtil.getInt(param.getPage_count(), ConfigValues.getRequestNum());
        Integer counts = brokerService.getCounts(param.getKeyword());
        List<Broker> brokerList = null;
        Integer limit_page_no = 0;
        if ((ValueUtil.getInt(param.getPage_no()) - 1) * page_size >= counts) {
            brokerList = new ArrayList<>();
        } else {
            if (page_no <= 0) {
                page_no = 1;
            }
            limit_page_no = (page_no - 1) * page_size;
            brokerList = brokerService.getBrokerAccountList(param.getKeyword(), param.getSort_field(),
                    param.getSort_type(), limit_page_no, page_size);
        }
        
        if (brokerList == null) {
            brokerList = new ArrayList<Broker>();
        }
        
        BrokerAccountListBackForm result = new BrokerAccountListBackForm();
        List<BrokerAccountListForm> dataList = new ArrayList<>();
        for (Broker broker : brokerList) {
            BrokerAccountListForm data = new BrokerAccountListForm();
            data.setBroker_id(broker.getBroker_id());
            data.setWx_account(broker.getWx_account());
            data.setBroker_name(broker.getBroker_name());
            data.setMobile(broker.getMobile());
            data.setWx_public_account(broker.getWx_public_account());
            data.setCreate_time(DateTimeUtil.toString(broker.getCreate_date()));
            data.setFr_code(broker.getFr_code());
            if (String.valueOf(ApplyStatus.PASS.getVal()).equals(broker.getReply_status())) {
                if (String.valueOf(CustomerStatus.NOMAL.getVal()).equals(broker.getBroker_status())) {
                    data.setStatus(String.valueOf(BrokerType.NOMAL.getVal()));
                } else if (String.valueOf(CustomerStatus.DISABLE.getVal()).equals(broker.getBroker_status())) {
                    data.setStatus(String.valueOf(BrokerType.DISABLE.getVal()));
                } else {
                    data.setStatus(String.valueOf(BrokerType.FROZEN.getVal()));
                }
            } else {
                if (String.valueOf(ApplyStatus.UNDER_REVIEW.getVal()).equals(broker.getReply_status())) {
                    data.setStatus(String.valueOf(BrokerType.UNDER_REVIEW.getVal()));
                } else {
                    data.setStatus(String.valueOf(BrokerType.FAIL.getVal()));
                }
            }
            dataList.add(data);
        }
        
        result.setPage_no(page_no);
        result.setRecord_count(counts);
        result.setData_list(dataList);
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public BrokerAccountInfoForm funcBrokerInfo(FollowBrokerForm param) {
        Broker c = brokerService.get(param.getBroker_id());
        BrokerAccountInfoForm result = new BrokerAccountInfoForm();
        if (c.getReply_status().equals(String.valueOf(ApplyStatus.PASS.getVal()))) {
            if (c.getBroker_status().equals(String.valueOf(CustomerStatus.NOMAL.getVal()))) {
                result.setStatus(String.valueOf(BrokerType.NOMAL.getVal()));
            } else if (c.getBroker_status().equals(String.valueOf(CustomerStatus.DISABLE.getVal()))) {
                result.setStatus(String.valueOf(BrokerType.DISABLE.getVal()));
            } else {
                result.setStatus(String.valueOf(BrokerType.FROZEN.getVal()));
            }
        } else {
            if (c.getReply_status().equals(String.valueOf(ApplyStatus.UNDER_REVIEW.getVal()))) {
                result.setStatus(String.valueOf(BrokerType.UNDER_REVIEW.getVal()));
            } else {
                result.setStatus(String.valueOf(BrokerType.FAIL.getVal()));
            }
        }
        
        result.setAccount_holder(c.getAccount_holder());
        result.setBank_account(c.getBank_account());
        result.setBank_name(c.getBank_name());
        result.setBroker_avatar(c.getBroker_avatar());
        result.setBroker_name(c.getBroker_name());
        result.setCertificate_id(c.getCertificate_id());
        result.setCertificate_type(c.getCertificate_type());
        result.setCity_name(c.getCity_name());
        result.setCreate_time(DateTimeUtil.toString(c.getCreate_date()));
        result.setEmail(c.getEmail());
        result.setFr_code(c.getFr_code());
        result.setFans_num(c.getFans_num());
        result.setId_card_img_back(c.getId_card_img_back());
        result.setId_card_img_front(c.getId_card_img_front());
        result.setId_no(c.getId_no());
        result.setJob_title(c.getJob_title());
        result.setMobile(c.getMobile());
        result.setProfile(c.getProfile());
        result.setProvince_name(c.getProvince_name());
        result.setSpeciality(c.getSpeciality());
        result.setWeibo_id(c.getWeibo_id());
        result.setWx_account(c.getWx_account());
        result.setWx_public_account(c.getWx_public_account());
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HSBCPSBackVO funcBrokerChangeStatus(BrokerStatusChangeForm param) {
        Broker broker = brokerService.get(param.getBroker_id());
        if (param.getBroker_type().equals(String.valueOf(BrokerType.PASS.getVal()))) {
            broker.setReply_status(String.valueOf(ApplyStatus.PASS.getVal()));
            brokerService.updateCAS(broker);
        } else if (param.getBroker_type().equals(String.valueOf(BrokerType.FAIL.getVal()))) {
            broker.setReply_status(String.valueOf(ApplyStatus.FAIL.getVal()));
            brokerService.updateCAS(broker);
        } else if (param.getBroker_type().equals(String.valueOf(BrokerType.FROZEN.getVal()))) {
            broker.setBroker_status(String.valueOf(CustomerStatus.FROZEN.getVal()));
            brokerService.updateCAS(broker);
        } else if (param.getBroker_type().equals(String.valueOf(BrokerType.DISABLE.getVal()))) {
            broker.setBroker_status(String.valueOf(CustomerStatus.DISABLE.getVal()));
            brokerService.updateCAS(broker);
        } else if (param.getBroker_type().equals(String.valueOf(BrokerType.NOMAL.getVal()))) {
            broker.setBroker_status(String.valueOf(CustomerStatus.NOMAL.getVal()));
            brokerService.updateCAS(broker);
        } else {
            return VOUtil.genErrorResult(ClientErr.BROKER_CANNOT_UPDATE, HSBCPSBackVO.class);
        }
        HSBCPSBackVO result = new HSBCPSBackVO();
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HSBCPSBackVO funcWhitelistImport(WhiteListFormData mobileList) {
        if (mobileList.getDataList() == null) {
            return VOUtil.genErrorResultVo(ClientErr.DATA_EMPTY_FAIL);
        }
        whitelistService.deleteByBrokerId(HSBCPSBizDataContext.getBrokerId());
        for (WhiteListForm mobile : mobileList.getDataList()) {
            Whitelist white = new Whitelist();
            white.setMobile(mobile.getMobile());
            white.setName(mobile.getName());
            white.setBroker_id(HSBCPSBizDataContext.getBrokerId());
            white.setCreate_by(HSBCPSBizDataContext.getClientIdNoException());
            white.setCreate_time(new Date());
            whitelistService.save(white);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public WhiteListBackForm funcWhitelistOutput(HSBCPSVO form) {
        List<WhiteListView> list = whitelistService.queryByBrokerId(HSBCPSBizDataContext.getBrokerId());
        List<WhiteListForm> returnList = new ArrayList<>();
        if (list != null) {
            returnList.addAll(list);
        }
        WhiteListBackForm result = new WhiteListBackForm();
        result.setData_list(returnList);
        return result;
    }
    
    //检测该租户下面是否已经有昵称，有返回true,没有返回false
    private boolean checkUserName(String name) {
        Integer total = brokerManagerService.checkUserName(name) + customerService.checkUserName(name);
        if (total > 0) {
            return true;
        }
        return false;
    }
    
    //检测管理平台管理员是否为云纪管理员
    //    private boolean managerJudge(String branchNo) {
    //        String[] branchSplit = branchNo.split(",");
    //        for (int i = 0; i < branchSplit.length; i++) {
    //            if (ConfigValues.getYunjiBranchNo().equals(branchSplit[i])) {
    //                return true;
    //            }
    //        }
    //        return false;
    //    }
    
    @Override
    public HSBCPSBackVO funcOperatorWhiteList(OperatorWhiteListForm form) {
        boolean updateFlag = false;
        JSONArray userArr = JSONArray.parseArray(form.getUser_list());
        if (userArr == null || userArr.isEmpty()) {
            return VOUtil.genErrorResult(ClientErr.REQUEST_PARA_ERROR, HSBCPSBackVO.class);
        }
        
        if ("1".equals(form.getWhite_flag())) {
            for (Object userObj : userArr) {
                JSONObject user = (JSONObject) userObj;
                if (!user.isEmpty() && !StringUtil.isEmpty(String.valueOf(user.get("mobile")))) {
                    Whitelist whiteList = whitelistService.queryByBrokerIdAndMobile(
                            HSBCPSBizDataContext.getBrokerId(), user.getString("mobile"));
                    if (whiteList != null) {
                        whitelistService.delete(whiteList.getWhitelist_id());
                        
                        updateFlag = true;
                    }
                }
            }
        } else {
            Whitelist white = new Whitelist();
            for (Object userObj : userArr) {
                JSONObject user = (JSONObject) userObj;
                if (!user.isEmpty() && !StringUtil.isEmpty(String.valueOf(user.get("mobile")))
                        && !StringUtil.isEmpty(String.valueOf(user.get("customer_name")))) {
                    white.setMobile(user.getString("mobile"));
                    white.setBroker_id(HSBCPSBizDataContext.getBrokerId());
                    white.setTenant_id(HSBCPSBizDataContext.getTenantId());
                    if (whitelistService.count(white) == 0) {
                        white.setMobile(user.getString("mobile"));
                        white.setName(user.getString("customer_name"));
                        white.setBroker_id(HSBCPSBizDataContext.getBrokerId());
                        white.setCreate_by(HSBCPSBizDataContext.getClientIdNoException());
                        white.setCreate_time(new Date());
                        whitelistService.save(white);
                        
                        updateFlag = true;
                    }
                }
            }
        }
        
        if (!updateFlag) {
            return VOUtil.genErrorResult(ClientErr.NO_RECORD_UPDATED, HSBCPSBackVO.class);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public HSBCPSBackVO funcPachSendSms(PachSendSMSForm form) {
        // 发送短信
        String str = smsExtService.sendMessage(form.getMobiles(), form.getContent());
        logger.debug(str);
        if (str == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.SMS_SEND_FAIL, SendSMSBackForm.class);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public LoginFormBackForm funcWebsiteRegister(WebsiteRegForm form) {
        String verify_code = form.getVerify_code();
        if (!validateCodeService.checkCode(verify_code, form.getMobile(), "", VerifySource.DAV_REGISTER.getVal())) {
            return VOUtil.genErrorResult(CommonErr.VERIFY_CODE_WRONG, LoginFormBackForm.class);
        }
        
        String broker_name = form.getApplicant_name();
        if (checkUserName(broker_name)) {
            return VOUtil.genErrorResult(ClientErr.USER_NAME_EXSIT, LoginFormBackForm.class);
        }
        //查询用户中心是否注册，已注册直接返回手机号已注册，没有注册先去用户中心注册
        Long user_id = null;
        FuncRegisterForm rform = null;
        if (ConfigValues.IsUserCenter()) {
            FuncLoginForm param = new FuncLoginForm();
            param.setLogin_account(form.getMobile());
            param.setUser_type("2");
            CheckRegisterBackVo vo = uCenterService.funcCheckRegister(param);
            if (VOUtil.isSuccess(vo)) {
                String is_register = vo.getIs_register();
                if ("1".equals(is_register)) {
                    return VOUtil.genErrorResult(ClientErr.MOBILE_REGISTERED, LoginFormBackForm.class);
                }
                //注册用户中心
                rform = new FuncRegisterForm();
                rform.setLogin_account(form.getMobile());
                String id_no = form.getId_no();
                //初始密码a+身份证号码后7位
                String pwd = "a" + id_no.substring(id_no.length() - 7, id_no.length());
                //前端入参加密，初始化时需加密两次
                pwd = MD5Util.encrypt(pwd).toLowerCase();
                rform.setAuth_password(MD5Util.encrypt(pwd));
                rform.setUser_type("2");
                rform.setAlias_name(form.getApplicant_name());
                rform.setRegister_flag("1");
                rform.setMobile(form.getMobile());
            }
        } else {
            BrokerManager brokerManager = brokerManagerService.getByMobile(form.getMobile());
            if (brokerManager != null) {
                return VOUtil.genErrorResult(ClientErr.MOBILE_REGISTERED, LoginFormBackForm.class);
            }
        }
        Broker broker = new Broker();
        String wx_account = form.getWx_account();
        //机构用户暂存租户ID999999
        Integer tenant_id = SysContants.COMPANY_TENANT_ID_DEFAULT;
        if (wx_account.equals(String.valueOf(WxAccountType.PERSONAL.getVal()))) {
            tenant_id = this.getPersinalTenantId(form.getApplicant_name());
        }
        if (rform != null) {
            //到用户中心注册
            rform.setTenant_id(tenant_id);
            UIDBackVo bvo = uCenterService.funcRegister(rform);
            if (VOUtil.isSuccess(bvo)) {
                //更新user_id到manager表
                user_id = bvo.getUser_id();
            } else {
                if ("10055".equals(bvo.getError_no())) {
                    return VOUtil.genErrorResult(ClientErr.USER_NAME_EXSIT, LoginFormBackForm.class);
                }
                return VOUtil.genErrorResult(BasicErrorCodes.USER_CENTER_INTERFACE_ERR, LoginFormBackForm.class);
            }
        }
        //设置基础信息
        broker.setWx_account(wx_account);
        broker.setMobile(form.getMobile());
        broker.setBroker_name(broker_name);
        broker.setBroker_status(String.valueOf(CustomerStatus.NOMAL.getVal()));
        String id_no = form.getId_no();
        //初始密码a+身份证号码后7位
        String pwd = "a" + id_no.substring(id_no.length() - 7, id_no.length());
        //前端入参加密，初始化时需加密两次
        pwd = MD5Util.encrypt(pwd).toLowerCase();
        broker.setPassword(MD5Util.encrypt(pwd));
        broker.setWx_public_account(form.getWx_public_account());
        broker.setBroker_key(UUID.randomUUID().toString());
        broker.setId_card_img_front(form.getIdcard_img_front());
        broker.setId_card_img_back(form.getIdcard_img_back());
        broker.setId_no(id_no);
        int third_pay_status = Integer.parseInt(form.getThird_flag());//0-不启用，1-启用
        broker.setThird_pay_status(third_pay_status);
        broker.setWx_develop_id(form.getWx_develop_id());
        broker.setBusiness_licence(form.getBusiness_licence());
        broker.setBank_name(form.getBank_name());
        broker.setBank_account(form.getBank_account());
        broker.setAccount_holder(form.getAccount_holder());
        broker.setCertificate_type(form.getCertificate_type());
        broker.setCertificate_id(form.getCertificate_id());
        broker.setFr_code(form.getFr_code());
        broker.setEmail(form.getEmail());
        broker.setCreate_date(new Date());
        broker.setApplicant_name(form.getApplicant_name());
        broker.setReply_status(String.valueOf(ApplyStatus.UNDER_REVIEW.getVal()));
        broker.setTenant_id(tenant_id);
        brokerService.save(broker);
        
        BrokerManager manager = new BrokerManager();
        manager.setName(broker.getApplicant_name());
        manager.setMobile(form.getMobile());
        manager.setPassword(MD5Util.encrypt(pwd));
        manager.setBroker_flag(1);
        manager.setBroker_id(broker.getBroker_id());
        manager.setCreate_time(new Date());
        manager.setTenant_id(tenant_id);
        manager.setDelete_flag(0);
        manager.setUser_id(user_id);
        brokerManagerService.save(manager);
        
        //云信注册
        brokerManagerService.yunxinRoomReg(broker, manager, true);
        //保存默认标签
        viewpointTagService.saveTagForBroker(broker);
        //注册金币系统
        GoldRegiste(broker);
        
        LoginFormBackForm result = new LoginFormBackForm();
        //保存新的用户会话
        String user_token = saveNewBrokerSession(manager, broker, manager.getBroker_flag() != 1, result,
                BrokerLoginType.WEB);
        result.setUser_token(user_token);
        result.setBroker_id(broker.getBroker_id());
        result.setAccess_token(AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal()));
        
        //生成分组
        ExtendGroupBuildDefaultForm defaultForm = new ExtendGroupBuildDefaultForm();
        defaultForm.setBroker_id(String.valueOf(broker.getBroker_id()));
        extendGroupT2.funcExtendGroupBuildDefault(defaultForm);
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public TenantForm funcGetTenant(HSBCPSVO form) {
        Tenant tenant = null;
        Integer tenantId = null;
        TenantForm tenantForm = new TenantForm();
        
        if (form.getTenant_id() != null && !form.getTenant_id().trim().isEmpty()) {
            tenantId = ValueUtil.getInt(form.getTenant_id());
            tenant = tenantService.get(form.getTenant_id());
            Integer maxTenantId = tenantService.getMax();
            if (tenant != null) {
                return VOUtil.genErrorResult(ClientErr.TENAN_HAS_EXIST, TenantForm.class);
            }
            if (tenantId > maxTenantId) {
                return VOUtil.genErrorResult(ClientErr.TENAN_ID_ERROR, TenantForm.class);
            }
            tenant = new Tenant();
            tenant.setTenant_id(tenantId);
            tenant.setTenant_key(UUID.randomUUID().toString().replace("-", ""));
            tenant.setCreate_date(new Date());
            tenantService.saveByTenant(tenant);
        } else {
            tenant = new Tenant();
            tenant.setTenant_key(UUID.randomUUID().toString().replace("-", ""));
            tenant.setCreate_date(new Date());
            tenantService.save(tenant);
        }
        
        tenantForm.setTenant_id(tenant.getTenant_id());
        tenantForm.setTenant_key(tenant.getTenant_key());
        return VOUtil.setSuccessResult(tenantForm);
    }
    
    @Override
    public RegisterOrLoginBackForm funcRegisterOrLogin(RegisterOrLoginForm form) {
        String mobile = form.getMobile();
        String password = form.getPassword();
        String verify_code = form.getVerify_code();
        //校验验证码
        if (!validateCodeService.checkCode(verify_code, mobile, "", VerifySource.DAV_REGISTER.getVal())) {
            return VOUtil.genErrorResult(CommonErr.VERIFY_CODE_WRONG, RegisterOrLoginBackForm.class);
        }
        RegisterOrLoginBackForm backForm = new RegisterOrLoginBackForm();
        Broker broker = this.brokerService.getByMobile(mobile);
        BrokerManager manager = new BrokerManager();
        //校验手机号是否注册        
        if (broker != null) {
            /***
             * 手机号已注册 1:审核通过2:审核中3:审核不通过4:待完善信息
             */
            manager = this.brokerManagerService.getByMobile(mobile);
            String user_token = saveNewBrokerSession(manager.getBroker_manager_id(), broker, BrokerLoginType.APP,
                    manager.getUser_id());
            backForm.setUser_token(user_token);
            backForm.setReply_status(broker.getReply_status());
            backForm.setBroker_id(broker.getBroker_id());
            backForm.setAccess_token(AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal()));
            return VOUtil.setSuccessResult(backForm);
        }
        //租户ID暂时新建，后续有待确认
        Tenant tenant = new Tenant();
        tenant.setCreate_date(new Date());
        tenant.setTenant_key(UUID.randomUUID().toString());
        tenantService.save(tenant);
        Integer tenant_id = tenant.getTenant_id();
        //简要登记投顾信息,设置为待完善信息状态
        broker = new Broker();
        broker.setMobile(mobile);
        broker.setPassword(MD5Util.encrypt(password));
        broker.setTenant_id(tenant_id);
        broker.setBroker_key(UUID.randomUUID().toString());
        broker.setReply_status(String.valueOf(ApplyStatus.WAIT.getVal()));
        broker.setCreate_date(new Date());
        brokerService.save(broker);
        //生成一个投顾管理员本身
        manager.setMobile(form.getMobile());
        manager.setPassword(MD5Util.encrypt(password));
        manager.setBroker_flag(1);
        manager.setBroker_id(broker.getBroker_id());
        manager.setTenant_id(tenant_id);
        manager.setCreate_time(new Date());
        manager.setDelete_flag(0);
        brokerManagerService.save(manager);
        
        //保存用户会话token
        String user_token = saveNewBrokerSession(manager.getBroker_manager_id(), broker, BrokerLoginType.APP,
                manager.getUser_id());
        backForm.setUser_token(user_token);
        backForm.setReply_status(broker.getReply_status());
        backForm.setBroker_id(broker.getBroker_id());
        backForm.setAccess_token(AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal()));
        return VOUtil.setSuccessResult(backForm);
    }
    
    private String saveNewBrokerSession(Long managerId, Broker broker, BrokerLoginType loginType, Long userCenterId) {
        Long client_id = managerId;
        PlatformType type = PlatformType.MANAGE;
        // 根据clientId 获取 客户的 access_token,获取到token 把当前的token 注销掉
        String clientIdToken = SessionHelper.getInstance().getSessionTokenByClientId(type,
                loginType.getVal() + client_id.toString());
        // 客户已经存在token，删除token
        if (!StringUtil.isBlank(clientIdToken)) {
            // 销毁会话令牌
            SessionHelper.getInstance().delete(clientIdToken);
        }
        CustomerCache identity = new CustomerCache();
        identity.setClient_id(client_id);
        identity.setUserCenterId(userCenterId);
        identity.setTenantId(broker.getTenant_id());
        identity.setBrokerId(broker.getBroker_id());
        //大V或者粉丝
        identity.setUserType(SysContants.SESSION_USER_TYPE_CLIENT);
        identity.setBroker(broker);
        identity.setBrokerLoginType(loginType.getVal());
        identity.setPlatformType(type.getValue());
        String access_token = SessionHelper.getInstance().renewAccess_token(identity);
        // 把生成的token保存到缓存
        SessionHelper.getInstance().saveNewClientIDSession(type, client_id, access_token, broker.getTenant_id(),
                loginType);
        
        return access_token;
    }
    
    @Override
    public HSBCPSBackVO funcBrokerDetailUpdate(BrokerDetailForm form) {
        Integer tenantId = HSBCPSBizDataContext.getTenantId();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        
        String broker_name = StringUtil.isEmpty(form.getBroker_name()) ? form.getApplicant_name() : form
                .getBroker_name();
        if (checkUserName(broker_name)) {
            return VOUtil.genErrorResult(ClientErr.USER_NAME_EXSIT, LoginFormBackForm.class);
        }
        Broker broker = this.brokerService.getById(broker_id, tenantId);
        if (null == broker) {
            return VOUtil.genErrorResult(ClientErr.NO_FOLLOW_BROKER, LoginFormBackForm.class);
        }
        String mobile = broker.getMobile();
        //设置基础信息
        broker.setWx_account(form.getWx_account());
        broker.setBusiness_licence(form.getBusiness_licence());
        broker.setCertificate_type(form.getCertificate_type());
        broker.setCertificate_id(form.getCertificate_id());
        broker.setOwn_organ(form.getOwn_organ());
        broker.setJob_title(form.getJob_title());
        broker.setProvince_name(form.getProvince_name());
        broker.setCity_name(form.getCity_name());
        broker.setSpeciality(form.getSpeciality());
        broker.setProfile(form.getProfile());
        broker.setFr_code(form.getFr_code());
        broker.setEmail(form.getEmail());
        broker.setBroker_name(broker_name);
        broker.setBroker_status(String.valueOf(CustomerStatus.NOMAL.getVal()));
        String pwd = MD5Util.encrypt(broker.getPassword());
        broker.setWx_public_account(form.getWx_public_account());
        
        broker.setCreate_date(new Date());
        broker.setApplicant_name(form.getApplicant_name());
        broker.setCompany(form.getCompany_name());
        broker.setAccount_holder(form.getAccount_holder());
        broker.setBank_account(form.getBank_account());
        broker.setBank_name(form.getBank_name());
        broker.setFans_num(StringUtil.isEmpty(form.getFans_num()) ? null : Integer.valueOf(form.getFans_num()));
        broker.setId_card_img_back(form.getIdcard_img_back());
        broker.setId_card_img_front(form.getIdcard_img_front());
        broker.setId_no(form.getId_no());
        broker.setWeibo_id(form.getWeibo_id());
        broker.setReply_status(String.valueOf(ApplyStatus.UNDER_REVIEW.getVal()));
        brokerService.update(broker);
        
        BrokerManager manager = this.brokerManagerService.getByMobile(mobile);
        if (null == manager) {
            manager = new BrokerManager();
            manager.setName(broker.getBroker_name());
            manager.setMobile(mobile);
            manager.setPassword(pwd);
            manager.setBroker_flag(1);
            manager.setBroker_id(broker.getBroker_id());
            manager.setCreate_time(new Date());
            manager.setTenant_id(tenantId);
            manager.setDelete_flag(0);
            brokerManagerService.save(manager);
        } else {
            manager.setName(broker.getBroker_name());
            brokerManagerService.update(manager);
        }
        
        //云信注册
        brokerManagerService.yunxinRoomReg(broker, manager, true);
        //保存默认标签
        String[] tags = ConfigValues.getDefaultViewpointTag();
        for (int i = 0; i < tags.length; i++) {
            String tagName = tags[i];
            ViewpointTag tag = new ViewpointTag();
            tag.setBroker_id(broker.getBroker_id());
            tag.setCreate_time(new Date());
            tag.setTag_name(tagName);
            tag.setTag_type(SysContants.SYSTEM_TAG_TYPE);
            tag.setOrder_num(i + 1);
            tag.setTenant_id(tenantId);
            viewpointTagService.save(tag);
        }
        
        /*//生成一条审核记录
        BrokerCheck brokerCheck = new BrokerCheck();
        brokerCheck.setBroker_id(broker.getBroker_id());
        brokerCheck.setCheck_manager(1);
        brokerCheck.setCheck_result("0");
        brokerCheck.setTenant_id(tenantId);
        brokerCheckService.save(brokerCheck);*/
        
        return VOUtil.genSuccessBackVo();
    }
    
    //    private Integer getNewTenantId(String branchNo, String tenantIdStr, String parentBranchNo, String branchName) {
    //        Integer tenantId = null;
    //        Tenant tenant = null;
    //        if (!StringUtil.isBlank(tenantIdStr)) {
    //            
    //            tenantId = Integer.parseInt(tenantIdStr.substring(0, tenantIdStr.length() - 4));
    //            String keyStart = tenantIdStr.substring(tenantIdStr.length() - 4);
    //            tenant = tenantService.get(String.valueOf(tenantId));
    //            if (!tenant.getTenant_key().startsWith(keyStart)) {
    //                tenant = null;
    //            } else {
    //                return tenant.getTenant_id();
    //            }
    //        } else if (!StringUtil.isBlank(branchNo)) {
    //            //有组织架构的投顾注册租户需要填写组织机构相关信息
    //            Tenant tenantBranch = tenantService.getByBranchNo(branchNo);
    //            if (tenantBranch == null) {
    //                tenantBranch = tenantService.getByBranchNo(parentBranchNo);
    //            }
    //            
    //            tenant = new Tenant();
    //            tenant.setCreate_date(new Date());
    //            tenant.setTenant_key(UUID.randomUUID().toString());
    //            tenant.setBranch_no(branchNo);
    //            tenant.setBranch_name(branchName);
    //            tenant.setParent_branch_no(parentBranchNo);
    //            if (tenantBranch == null) {
    //                tenant.setBranch_grade("1");
    //            } else {
    //                tenant.setBranch_grade(tenantBranch.getBranch_grade());
    //            }
    //            tenantService.save(tenant);
    //        }
    //        
    //        if (tenant == null) {
    //            tenant = new Tenant();
    //            tenant.setCreate_date(new Date());
    //            tenant.setTenant_key(UUID.randomUUID().toString());
    //            tenantService.save(tenant);
    //        }
    //        tenant = tenantService.getByKey(tenant.getTenant_key());
    //        return tenant.getTenant_id();
    //    }
    
    private boolean chechNecsseryInfo(BatchImportBrokerForm form) {
        String broker_name = form.getBroker_name();
        
        if (StringUtil.isBlank(broker_name) || StringUtil.isBlank(form.getMobile())) {
            return false;
        }
        /*if (checkUserName(broker_name)) {
            return false;
        }*/
        BrokerManager brokerManager = brokerManagerService.getByMobile(form.getMobile());
        if (brokerManager != null) {
            return false;
        }
        return true;
    }
    
}
